package tuvienna.jade.participant;

import jade.core.AID;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import java.io.IOException;

import tuvienna.jade.CentralRandom;
import tuvienna.jade.Constants;

/**
 * Handling the registration of a participant to a table
 */
public class RegisterAtTableBehaviour extends Behaviour {

	private static final long serialVersionUID = 1809253933702899176L;
	private boolean done = false;
	private int step = 0;
	protected ParticipantAgent participant;
	private AID table;
	private MessageTemplate mt;
	
	public RegisterAtTableBehaviour(ParticipantAgent participant, AID table) {
		super();
		this.participant = participant;
		this.table = table;
	}

	public void action() {
		switch(step) {
		case 0:
			try {
				ACLMessage registrationRequest = new ACLMessage(ACLMessage.REQUEST);
				registrationRequest.addReceiver(table);
				registrationRequest.setContentObject(participant.getInterests());

				registrationRequest.setConversationId(getConversationID());
				String msgId = participant.getLocalName()+"/"+table.getLocalName()
						+"/"+CentralRandom.nextInt(10000);
				registrationRequest.setReplyWith(msgId);
				participant.send(registrationRequest);
				step = 1;
				
				mt = MessageTemplate.and(MessageTemplate.MatchConversationId(getConversationID()),
										 MessageTemplate.MatchInReplyTo(msgId));
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case 1:
			ACLMessage reply = participant.receive(mt);
			if (reply != null) {
				if (reply.getPerformative() == ACLMessage.AGREE) {
					success(reply);
				} else {
					failure(reply);
				}
				done = true;
			} else { 
				block();
			}
			break;
		}
		
	}

	public boolean done() {
		return done;
	}
	
	protected String getConversationID() {
		return Constants.REGISTRATION_REQUEST;
	}
	
	protected void success(ACLMessage reply) {
		participant.setTable(reply.getSender());	
	}
	
	protected void failure(ACLMessage reply) {
	}

	
}